import { userLogin, logout, getUserInfo } from '@/api/administrator'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '../../router/routes'

const tokenKeyName = 'Authorization'
const user = {
  // 当需要token时调用getToken()函数
  state: {
    userInfo: null,
    token: getToken(),
    avatar: '',
    bool:'',
    roles: []
  },
  // console.log("roles")
  getters: {
    token: state => state.token,
    roles: state => state.roles,
    avatar: state => state.avatar
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      if(userInfo.roleId == 14 || userInfo.roleId == 24){
        state.bool = true
      } else {
        state.bool = false
      }
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    csh(csh){
      console.log(11,csh)
    },
    // 箭头函数的写法
    // SET_TOKEN: (state, token) => {
    //   console.log(state,'state')
    //   console.log(token,'token')
    //   state.token = token
    // },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },
  actions: {
    // 用户名登录
    // 此处的res将会返回到index.vue页面
    async userLogin({ commit }, userInfo) {
      let res
      try {
        res = await userLogin(userInfo)
        if (res.code === 1) {
          commit('SET_TOKEN', res.data)
          setToken(res.data)
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 调用接口从后台获取用户信息
    // 将res.data即用户的所有信息存储，res.data.managerType为管理员类型数据
    // 从state.token里面取到token的数据，然后调用接口函数getUserInfo获得用户信息
    async getUserInfo({ commit, state }) {
      let res
      try {
        res = await getUserInfo(state.token)
        console.log(res);
        if (res.code === 1) {
          commit('SET_USERINFO', res.data)
          commit('SET_ROLES', res.data.roleId)
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 登出
    async LogOut({ commit }) {
      let res
      try {
        res = await logout()
        commit('SET_TOKEN', '')
        removeToken()
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 前端 登出
    FedLogOut({ commit }) {
      console.log('走了');
      return new Promise(resolve => {
        console.log('resolve',resolve);
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
